if __name__ == '__main__':
  # Setup script environ
  import os
  import sys
  FILE_ROOT = os.path.realpath(os.path.dirname(__file__))
  file_path = lambda *x: os.path.join(FILE_ROOT, *x)

  sys.path.append(file_path('..'))
  sys.path.append(file_path('..', 'packages'))

  from django.core.management import setup_environ
  from transport import settings
  setup_environ(settings)


from django.contrib.auth.models import User
from django.db.models import Count
from django.db.models import Q

from django.contrib.gis.geos import Point
from django.contrib.gis.measure import D

from transport.models import GPSLog, Location

from datetime import datetime, time, timedelta

RADIUS = 500 # meters
CONVERT = 1000000.0
HOURS_AHEAD = 4

def add_hours(tm, hours):
  fulldate = datetime(1,1,1,tm.hour,tm.minute,tm.second)
  fulldate = fulldate + timedelta(hours=hours)
  return fulldate.time()

def time_condition(t1, hours_to_add, user_id):
  t2 = add_hours(t1, hours_to_add)
  if t2 < t1:
    return Q(user__id=user_id) & (Q(time__gt=t1, time__lt=time.max) |
                                  Q(time__gt=time.min, time__lt=t2))
  else:
    return Q(user__id=user_id) & Q(time__gt=t1, time__lt=t2)

def predict(user_id, ptime, x, y):
  my_p = Point(x, y)
  # TODO: take away
  my_l = Location.objects.filter(
    user__id=user_id,
    geom__distance_lt=(my_p, D(m=RADIUS))
  )
  print my_l
  my_l_ids = [l.id for l in my_l]

  likely_l = GPSLog.objects.filter(time_condition(ptime, HOURS_AHEAD, user_id)) \
      .values('location').annotate(lcount=Count('location'))

  likeliest = None
  highest_count = None
  for i, l in enumerate(likely_l):
    if l['location'] not in my_l_ids and \
       (likeliest is None or highest_count < l['lcount']):
      likeliest = l['location']
      highest_count = l['lcount']
  if likeliest is not None:
    l_l = Location.objects.get(id=likeliest)
    return (l_l.geom.get_x(), l_l.geom.get_y())
  else:
    return None


if __name__ == '__main__':

  print predict(
    user_id=2,
    ptime=time(23, 40, 0),
    x=12.471798,
    y=55.756462 

    #x=12.472587,
    #y=55.756482
  )
 
